//
//  StatusCellPictureView.swift
//  新浪微博
//
//  Created by 焦林生 on 15/11/11.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit
import SDWebImage

/// 微博配图视图 Cell 可重用标识符
private let StatusCellPictureViewCellId = "StatusCellPictureViewCellId"

/// 配图视图格子间距
private let StatusCellPictureItemMargin: CGFloat = 8

//微博配图视图
class StatusCellPictureView: UICollectionView {

    //MARK: - 构造函数
    init() {
         //设置布局
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = StatusCellPictureItemMargin
        layout.minimumLineSpacing = StatusCellPictureItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        //注册可重用cell
        registerClass(StatusCellPictureViewCell.self, forCellWithReuseIdentifier: StatusCellPictureViewCellId)
        //设置数据源  自己当自己的数据源
        dataSource  = self
        
        //设置代理
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //微博视图模型
    var viewModel: StatusViewModel? {
    
        didSet {
        
           sizeToFit()
            // 刷新数据 － 如果不刷新，后续的 collectionView 一旦被复用，不再调用数据源方法
            reloadData()
        }
    }
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return valcViewSize()
    }
    


}
// MARK: - UICollectionViewDataSource,UICollectionViewDelegate
extension StatusCellPictureView: UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let userInfo = [LJStatusSelectPhotoURLKey: viewModel!.thumbnailUrls!,
            LJStatusSelectPhotoIndexPathKey: indexPath]
        
        NSNotificationCenter.defaultCenter().postNotificationName(LJStatusSelectPhotoNotification,
            object: self,
            userInfo: userInfo)
        
    }

    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusCellPictureViewCellId, forIndexPath: indexPath) as! StatusCellPictureViewCell
        cell.imageURL = viewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }

}

// MARK: - PhotoBrowserPresentDelegate
extension StatusCellPictureView: PhotoBrowserPresentDelegate {
    /**
    参与转场动画图像视图
    
    - parameter indexPath: 照片索引
    
    - returns: 参与转场动画的全新视图
    */
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let key = viewModel!.thumbnailUrls![indexPath.item].absoluteString
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        iv.sizeToFit()
        
        return iv
    }
    
    /**
    展现转场图像起始位置
    
    - parameter indexPath: 当前选中照片索引
    
    - returns: 相对于屏幕的位置
    */
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
    
        guard let cell = self.cellForItemAtIndexPath(indexPath) else {
        
        
            return CGRectZero
        }
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
    }
    
    /**
    展现动画结束时的屏幕位置
    
    - parameter indexPath: 照片索引
    
    - returns: 相对于屏幕的位置
    */
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
    
        let key = viewModel!.thumbnailUrls![indexPath.item].absoluteString
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
        
            return CGRectZero
        }
        
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size
        .width
        var y: CGFloat = 0
        
        let screenHeight = UIScreen.mainScreen().bounds.height
        if h < screenHeight {
        
            y = (screenHeight - h) * 0.5
        }
        return CGRect(x: 0, y: y, width: w, height: h)
        
    }
}

// MARK: - 视图大小
extension StatusCellPictureView {


    //计算视图大小
    private func valcViewSize() -> CGSize {
    
    
        //默认每行3长图片
        let rowCount: CGFloat = 3
        //collectionvew总宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusCellPictureItemMargin) / rowCount
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        //设置itemSize
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        //1 单图
        if count == 0 {
        
            return CGSizeZero
        }
        //2 单图
        if count == 1 {
          //临时设置单图大小
            var size =  CGSize(width: 150, height: 120)
            
            //提取单图
            // 利用 SDWebImage 检查本地的缓存图像 - key 就是 url 的完整字符串
            // 问：SDWebImage 是如何设置缓存图片的文件名 完整 URL 字符串 -> `MD5`
            let key = viewModel?.thumbnailUrls![0].absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            {
            
                size = image.size
            }
            //过窄处理  针对长图
            size.width = size.width < 40 ? 40 : size.width
            
            //过宽的处理
            if size.width > 300 {
            //按比例放缩
                let w: CGFloat = 300
                let h = size.height * (w / size.width)
                
                size = CGSize(width: w, height: h)
            }
            
            
            //内部图片的大小
            layout.itemSize = size
            
            //配图视图的大小
            return size
        }
        //3 四张图 返回2 * 2
        if count == 4 {
        
            let w = itemWidth * 2 + StatusCellPictureItemMargin
            return CGSize(width: w, height: w)
        }
        // 4. 其它
        // 行数
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        //一行几个 * 每个宽度  + 每个图片之间的间距 = 总宽度
        let w = rowCount * itemWidth + (rowCount - 1) * StatusCellPictureItemMargin + 1
        //行数 * 每个高度 + 每个图片之间的间距
        let h = row * itemWidth + (row - 1) * StatusCellPictureItemMargin + 1
        
        return CGSize(width: w, height: h)
    }
}
//MARK: 微博配图cell
private class StatusCellPictureViewCell: UICollectionViewCell {
    //下载图片
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,
                options: [.RetryFailed, .LowPriority])
            
            //根据文件的扩展名判断是否是gif,但是不是所有的gif都会动
            let gg = ((imageURL?.absoluteString ?? "") as NSString).pathExtension.lowercaseString
            gifIconView.hidden = (gg != "gif")
        }
    }
    
    //MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        //1 添加控件
        contentView.addSubview(iconView)
        iconView.addSubview(gifIconView)
        
        //2 设置布局 cell会变化 不同的cell大小可能不一样
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        gifIconView.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(iconView.snp_right)
            make.bottom.equalTo(iconView.snp_bottom)
        }
        
    }
    
    // MARK: - 懒加载控件
    /// 图像视图
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        //设置填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        //需要裁切图片
        iv.clipsToBounds = true
        
        return iv
        }()
    
    //GIF标记图片
    private lazy var gifIconView: UIImageView = UIImageView(imageName: "timeline_image_gif")

}





